/*
 * @# CacheAndDbCase.java 2011-11-7 下午05:53:58
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.experiments.redis;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

/**
 * @author alvin hwang
 */
public class CacheAndDbCase {
	
	private static final String HOST = "192.168.1.105";
	private static final int PORT = 6379;
	
	private static Logger log = LoggerFactory.getLogger(WholeCacheCase.class);
	
	private Jedis jedis;
	
	public CacheAndDbCase() {
		jedis = new Jedis(HOST, PORT);
	}
	
	public void clear(Long id) {
		jedis.del("redis-demo-" + id);
	}
	
	public RedisDemo get(Long id) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		
		Map<String, String> cache = jedis.hgetAll("redis-demo-" + id);
		
		if (MapUtils.isEmpty(cache)) {
			NoneCacheCase noneCacheCase = new NoneCacheCase();
			RedisDemo data = noneCacheCase.get(id);
			
			cache = put(data);
		}
		RedisDemo data = new RedisDemo();
		data.setId(id);
		data.setName(cache.get("name"));
		data.setDescription(cache.get("description"));
		data.setAge(Integer.parseInt(cache.get("age")));
		
		stopWatch.stop();
		//log.debug("CacheAndDbCase get {} 运行时间为: {}", id, stopWatch.toString());
		
		return data;
	}
	
	private Map<String, String> put(RedisDemo data) {
		Map<String, String> cache = new HashMap<String, String>();
		cache.put("name", data.getName());
		cache.put("description", data.getDescription());
		cache.put("age", String.valueOf(data.getAge()));
		
		jedis.hmset("redis-demo-" + data.getId(), cache);
		
		return cache;
	}
	
	public void run(int loops, boolean same) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		
		for (int i = 0; i < loops; i++) {
			get(Long.valueOf(same ? 1 : (i + 1)));
		}
		
		stopWatch.stop();
		//log.debug("CacheAndDbCase get 遍历次数: {} 总运行时间为: {}", loops, stopWatch.toString());
	}
	
	public static void main(String[] args) {
		CacheAndDbCase testcase = new CacheAndDbCase();
		
		//testcase.run(5000, true);
		
		for (int i = 0; i < 5; i++) {
			//testcase.clear(Long.valueOf(i + 1));
			testcase.get(Long.valueOf(i + 1));
		}
		log.debug("done");
	}
}
